package BaseActivity;

import android.app.Activity;
import android.app.ActivityManager;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.LayoutAnimationController;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.example.administrator.drinkdevice.BuildConfig;
import com.example.administrator.drinkdevice.MainActivity;
import com.example.administrator.drinkdevice.NetworkConnectChangedReceiver;
import com.example.administrator.drinkdevice.R;

import org.json.JSONObject;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import Const.PublicDefine;
import Entity.ActivityResult;
import Entity.RequestPermissionsResult;
import Helper.Msgbox;
import Interface.IAsynCallBackListener;
import Service.SysService;
import ViewModel.Base_ViewModel;
import ViewModel.SqlliteManage_ViewModel;


/**
 * Created by 王彦鹏 on 2017-12-11.
 */

public class BaseActivity extends AppCompatActivity {

    private IAsynCallBackListener callBackListener;
    protected int TimeOutClose = 30;//自动关闭
    protected NetworkConnectChangedReceiver networkConnectChangedReceiver = new NetworkConnectChangedReceiver();

    private class OnLongClickListenerImpl implements View.OnLongClickListener {

        @Override
        public boolean onLongClick(View view) {
            try {
                if (BuildConfig.DEBUG) {
                    SqlliteManage_ViewModel sqlliteManage = new SqlliteManage_ViewModel(view.getContext());
                    sqlliteManage.Show();
                }
            } catch (Exception e) {
                System.out.println(e);

            }
            return true;
        }


    }

    //判断Activity在当前激活状态
    protected static boolean isTopActivity(Activity activity) {
        String packageName = activity.getPackageName();
        ActivityManager activityManager = (ActivityManager) activity
                .getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningTaskInfo> tasksInfo = activityManager.getRunningTasks(1);
        if (tasksInfo.size() > 0) {
            // 应用程序位于堆栈的顶层
            if (activity.getClass().getName().equals(tasksInfo.get(0).topActivity.getClassName())) {
                return true;
            }
        }
        return false;
    }

    public void RequestPermission(String pname, final IAsynCallBackListener callback) {
        callBackListener = callback;
        /// Manifest.permission.READ_CONTACTS
        if (ContextCompat.checkSelfPermission(this, pname) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, new String[]{pname}, 0);
        } else {

        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON, WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);

        IntentFilter filter = new IntentFilter();
        filter.addAction("android.net.conn.CONNECTIVITY_CHANGE");
        filter.addAction("android.net.wifi.WIFI_STATE_CHANGED");
        filter.addAction("android.net.wifi.STATE_CHANGE");

        registerReceiver(networkConnectChangedReceiver, filter);

        View view = findViewById(android.R.id.content);
        view.setOnLongClickListener(new OnLongClickListenerImpl());

        //InitViewAnim();


    }

    @Override
    protected void onDestroy() {
        unregisterReceiver(networkConnectChangedReceiver);
        super.onDestroy();
    }

    public boolean CheckPermission(String pname) {
        return ContextCompat.checkSelfPermission(this, pname) == PackageManager.PERMISSION_GRANTED;
    }

    @Override
    public void onRequestPermissionsResult(int requestCode,
                                           String permissions[], int[] grantResults) {
        switch (requestCode) {
            case 0: {
                if (grantResults.length > 0) {
                    List<RequestPermissionsResult> permissionsResultList = new ArrayList<RequestPermissionsResult>();
                    RequestPermissionsResult res = new RequestPermissionsResult();
                    for (int i = 0; i < permissions.length; i++) {
                        res.setRequestRes(grantResults[i]);
                        res.setPermissionsName(permissions[i]);
                        permissionsResultList.add(res);
                    }
                    if (callBackListener != null) {
                        callBackListener.onFinish("", permissionsResultList);
                    }
                } else {
                    if (callBackListener != null) {
                        callBackListener.onFinish(null, null);
                    }
                }
                callBackListener = null;
                return;
            }
        }

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {

        try {
            PublicDefine.enjoyCard.SetIntent(this, getIntent());
        } catch (Exception e) {
            StringWriter sw = new StringWriter();
            e.printStackTrace(new PrintWriter(sw, true));
            Helper.Log.write("Exception", sw.toString());
            e.printStackTrace();
        }
        if (callBackListener != null) {
            try {
                ActivityResult res = new ActivityResult();
                res.setRequestCode(requestCode);
                res.setResultCode(resultCode);
                res.setData(data);
                callBackListener.onFinish("", res);
            } catch (Exception e) {
                StringWriter sw = new StringWriter();
                e.printStackTrace(new PrintWriter(sw, true));
                Helper.Log.write("Exception", sw.toString());
                e.printStackTrace();
            }
        }
        callBackListener = null;
        super.onActivityResult(requestCode, resultCode, data);
    }

    @Override
    protected void onPause() {
        Log.d("Activity 休眠", getClass().getName());
       /* try {
            PublicDefine.enjoyCard.SetIntent(null, null);
        } catch (Exception e) {
            StringWriter sw = new StringWriter();
            e.printStackTrace(new PrintWriter(sw, true));
            Helper.Log.write("Exception", sw.toString());
            e.printStackTrace();
        }*/
        super.onPause();
    }

    //在Activity显示的时候，我们让NFC前台调度系统处于打开状态
    @Override
    protected void onResume() {
        Log.d("Activity 启动", getClass().getName());
        Msgbox.hideBottomUIMenu(this.getWindow());
        try {
            if (PublicDefine.enjoyCard != null) {
                PublicDefine.enjoyCard.SetIntent(this, getIntent());
            }
        } catch (Exception e) {
            StringWriter sw = new StringWriter();
            e.printStackTrace(new PrintWriter(sw, true));
            Helper.Log.write("Exception", sw.toString());
            e.printStackTrace();
        }
        super.onResume();

    }

    @Override
    public void finish() {
        super.finish();
        overridePendingTransition(android.R.anim.slide_in_left, android.R.anim.slide_out_right);

    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        try {
            if (keyCode == KeyEvent.KEYCODE_BACK) {
                onBackPressed();
                finish();
                return true;
            }
            return false;
        } catch (Exception e) {
            return false;
        }
    }

    protected void StartActivityForResult(Class<?> cls, IAsynCallBackListener callback, JSONObject jsonobj) {
        callBackListener = callback;
        Intent intent = new Intent();
        intent.setClass(this, cls);
        if (jsonobj != null) {
            intent.putExtra("request", jsonobj.toString());
        }
        startActivityForResult(intent, 0);
        overridePendingTransition(R.anim.slide_in_from_right, R.anim.slide_out_from_left);
    }

    public void StartActivityForResult(Class<?> cls, IAsynCallBackListener callback) {
        StartActivityForResult(cls, callback, null);
    }

    public void StartActivityForResult(Class<?> cls, JSONObject jsonobj) {
        StartActivityForResult(cls, null, jsonobj);
    }

    public void StartActivityForResult(Class<?> cls) {
        StartActivityForResult(cls, null, null);
    }

    protected String GetExceptionMsg(Throwable e) {
        if (e.getCause() != null) {
            return GetExceptionMsg(e.getCause());
        } else {
            return e.getMessage();
        }
    }

    protected int GetRandomAnimResId() {
        Random random = new Random();
        int r = Math.abs(random.nextInt());
        switch (r % 4) {
            case 0:
                return R.anim.anim_in_top;
            case 1:
                return R.anim.anim_in_bottom;
            case 2:
                return R.anim.anim_in_left;
            case 3:
                return R.anim.anim_in_right;
            default:
                return R.anim.anim_in_left;
        }
    }

    private void InitViewAnim() {
        List<View> list = getAllChildViews(this.getWindow().getDecorView());
        for (View v : list) {
            if (v == list.get(1)){
                continue;
            }
            if (v instanceof ViewGroup) {

                Animation animation = AnimationUtils.loadAnimation(this, GetRandomAnimResId());
                //得到一个LayoutAnimationController对象；
                LayoutAnimationController controller = new LayoutAnimationController(animation);

                //设置控件显示的顺序；
                controller.setOrder(LayoutAnimationController.ORDER_RANDOM);

                //设置控件显示间隔时间；

                controller.setDelay((float) 0.2);

                //为ListView设置LayoutAnimationController属性；
                ((ViewGroup) v).setLayoutAnimation(controller);
            }
        }
    }

    private List<View> getAllChildViews(View view) {
        List<View> allchildren = new ArrayList<View>();
        if (view instanceof ViewGroup) {
            ViewGroup vp = (ViewGroup) view;
            allchildren.add(vp);
            for (int i = 0; i < vp.getChildCount(); i++) {
                View viewchild = vp.getChildAt(i);
                //再次 调用本身（递归）
                allchildren.addAll(getAllChildViews(viewchild));
            }
        } else {
            allchildren.add(view);
        }
        return allchildren;
    }

    public static String encodeCardNo(String cardNo) {
        if (cardNo == null){
            return "";
        }
        if (cardNo.equals("--")){
            return cardNo;
        }
        switch (cardNo.length()) {
            case 0:
                return cardNo;
            case 1:
                return "*";
            case 2:
                return cardNo.substring(0, 1) + "*";
            default:
                String encodeStr = "";
                int repeatNum = 0;
                if (cardNo.length() > 1){
                    if (cardNo.length()-2 < 5){
                        repeatNum = cardNo.length()-2;
                    } else {
                        repeatNum = 4;
                    }
                }
                for (int i = 0; i < repeatNum; i++) {
                    encodeStr += "*";
                }
                return cardNo.substring(0, cardNo.length()-encodeStr.length()-1) + encodeStr + cardNo.substring(cardNo.length()-1, cardNo.length());
        }
    }

    /**
     * 点击空白区域隐藏键盘.
     */
    @Override
    public boolean onTouchEvent(MotionEvent event) {
        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        if (event.getAction() == MotionEvent.ACTION_DOWN) {
            if (this.getCurrentFocus() != null) {
                if (this.getCurrentFocus().getWindowToken() != null) {
                    imm.hideSoftInputFromWindow(this.getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
                }
            }
        }
        return super.onTouchEvent(event);
    }


    @Override
    public boolean dispatchTouchEvent(MotionEvent me) {
        if (me.getAction() == MotionEvent.ACTION_DOWN) {  //把操作放在用户点击的时候
            View focusView = this.getCurrentFocus();
            if (focusView != null) {
                if (isShouldHideKeyboard(focusView, me)) { //判断用户点击的是否是输入框以外的区域
                    clearFocus(focusView);
                }
            }
        }
        return super.dispatchTouchEvent(me);
    }

    //判断得到的焦点控件是否包含EditText
    private boolean isShouldHideKeyboard(View v, MotionEvent event) {
        if (v != null && (v instanceof EditText)) {
            int[] l = {0, 0};
            v.getLocationInWindow(l);
            int left = l[0],    //得到输入框在屏幕中上下左右的位置
                    top = l[1],
                    bottom = top + v.getHeight(),
                    right = left + v.getWidth();
            if (event.getX() > left && event.getX() < right
                    && event.getY() > top && event.getY() < bottom) {
                // 点击位置如果是EditText的区域，忽略它，不收起键盘。
                return false;
            } else {
                return true;
            }
        }
        // 如果焦点不是EditText则忽略
        return false;
    }

    //打开或隐藏软键盘
    public void clearFocus(View view) {
        if (view != null) {
            view.clearFocus();
            InputMethodManager mInputMethodManager = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
            mInputMethodManager.hideSoftInputFromWindow(view.getWindowToken(), 0);
        }
    }

    public void alert(final String info) {
        Message msg = new Message();
        msg.obj = new IAsynCallBackListener() {
            @Override
            public void onFinish(Object sender, Object data) {
                View toastRoot = getLayoutInflater().inflate(R.layout.my_toast, null);
                Toast toast=new Toast(getApplicationContext());
                toast.setView(toastRoot);
                TextView tv=(TextView)toastRoot.findViewById(R.id.TextViewInfo);
                tv.setText(info);
                toast.setGravity(Gravity.CENTER, 0, 0);
                toast.show();
            }

            @Override
            public void onError(Object sender, Exception e) {

            }
        };
        mHandler.sendMessage(msg);
    }

    public Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.obj instanceof IAsynCallBackListener) {
                ((IAsynCallBackListener) msg.obj).onFinish("", msg.arg1);
            }
        }
    };
}
